package com.matrix.socket;

import java.io.*;
import java.net.Socket;

public class ServerThread extends Thread{
    private Socket socket = null;
    private InputStream is;
    private InputStreamReader isr = null;
    private BufferedReader br = null;
    private OutputStream os = null;
    private PrintWriter pw = null;
    private String str = null;
    private String reply = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        super.run();

        try {
            is = socket.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }

        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        try {
            while((str = br.readLine()) != null){
                System.out.println("收到客户端消息：" + str);
                socket.shutdownInput();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            os = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pw = new PrintWriter(os);
        reply = "服务器已经收到消息。";
        pw.write(reply);
        pw.flush();
        try {
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
